package easy.相交链表;


import java.util.HashSet;
import java.util.Set;

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> visited = new HashSet<ListNode>();
        ListNode temp = headA;
        while (temp != null) {
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (temp != null) {
            if (visited.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }

    public static void main(String[] args) {
        // 创建节点
        ListNode n1 = new ListNode(4);
        ListNode n2 = new ListNode(1);
        ListNode n3 = new ListNode(5);
        ListNode n4 = new ListNode(6);
        ListNode n5 = new ListNode(1);
        ListNode n6 = new ListNode(8);
        ListNode n7 = new ListNode(4);
        ListNode n8 = new ListNode(5);
        // 连接节点
        n1.next = n2;
        n2.next = n6;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        n6.next = n7;
        n7.next = n8;
        // head 指向第一个节点
        ListNode head = n1;
        ListNode head2 = n3;
        Solution solution = new Solution();
        System.out.println(solution.getIntersectionNode(head, head2));
    }
}
